package interviewClassic150;

import java.util.HashMap;
import java.util.Map;

public class ContainsNearbyDuplicate {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        //定义一个map，key为nums中的元素值，value为上次出现这个值的索引
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int cur = nums[i];
            if (map.containsKey(cur)) {
                //判断是否满足题设条件
                int lastIndex = map.get(cur);
                if (i - lastIndex <= k) return true;
            }
            //将当前元素存放到map中
            map.put(cur,i);
        }
        return false;
    }
}
